import React, {useEffect, useRef, useState} from 'react';
import {
    Button,
    Card,
    Image,
    Space,
    Table,
    Form,
    Input,
    Select,
    Cascader,
    DatePicker,
    InputNumber, Upload, Tooltip, message, Modal
} from "antd";
import {
    reqAddActivity,
    reqDeleteActivity,
    reqGetActivityList,
    reqUpdateActivity
} from "../../../api/backStage/backStageApi";
import {DeleteOutlined, EditOutlined, LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import ReactQuill from "react-quill";
import options from "./options";
import dayjs from "dayjs";
import axios from "axios";
import moment from "moment";
import {debounce} from "lodash";


const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
};
const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};

// 富文本编辑器的自定义工具栏
const modules = {
    // 方式1: 可以是简单的一维数组配置
    // toolbar: ["bold", "italic", "underline", "strike", "blockquote"]
    // 方式2: 可以配置二维数组，进行多个选项的配置
    // 或者针对某一个配置项的key值，进行配置
    toolbar: [
        'bold', 'italic', 'underline',
        {header: 1}, {header: 2},
        'blockquote', 'code-block', 'code', 'link',
        {list: 'ordered'}, {list: 'bullet'},
        'image',
    ]
    // 方式3: 可以自己指定工具栏的容器
}
const AdminActivity = () => {

    const [newActivity, setNewActivity] = useState(false)
    const [updateActivity, setUpdateActivity] = useState(false)
    const [form] = Form.useForm()

    const [activityListData, setActivityListData] = useState()
    const [activityId, setActivityId] = useState(null)
    const [imageUrl, setImageUrl] = useState()
    const [editCoverLoading, setEditCoverLoading] = useState(false);
    const [content1, setContent] = useState('')

    const [open, setOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [modalText, setModalText] = useState('确认删除吗？删除之后不可恢复!');

    useEffect(() => {
        getActivityList()
    }, [])
    const getActivityList = async () => {
        const result = await reqGetActivityList()
        setActivityListData(result.data)
    }

    useEffect(() => {
       if (updateActivity){
           form.setFieldValue({
               cover:imageUrl
           })
       }
    },[imageUrl])

    const columns = [
        {
            title: '封面',
            dataIndex: 'cover',
            key: 'cover',
            width: 100,
            render: (_, record) => (
                <Image width={150} src={record.cover}/>
            )
        },
        {
            title: '活动名称',
            dataIndex: 'activity_name',
            key: 'activity_name',
            width: 150,
            render: (text) => <a>{text}</a>,
        },
        {
            title: '活动日期',
            dataIndex: 'start_time',
            key: 'start_time',
            width: 150,
            render: (text) => <span>{moment(text).format('YYYY-MM-DD')}</span>
        },
        {
            title: '活动地点',
            dataIndex: 'place',
            key: 'place',
            width: 150,
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            render: (_, record) => (
                <Space size="middle">
                    <Tooltip title="修改">
                        <Button onClick={() => editActivity(record)} type="primary"
                                style={{backgroundColor: '#ffa500'}}>
                            <EditOutlined/>
                        </Button>
                    </Tooltip>
                    <Tooltip title="删除">
                        <Button onClick={() => deleteActivity(record.id)} type="primary" danger>
                            <DeleteOutlined/>
                        </Button>
                    </Tooltip>
                </Space>
            ),
        },
    ];

    //新增按钮
    const addNewActivity = () => {
        form.resetFields()
        setImageUrl(null)
        setNewActivity(true)
    }

    //取消按钮
    const cancel = () => {
        setImageUrl(null)
        form.resetFields()
        setUpdateActivity(false)
        setNewActivity(false)
    }


    //修改活动
    const editActivity = (record) => {
        setUpdateActivity(true)
        setActivityId(record.id)
        setContent(record.content)
        setImageUrl([record.cover])
        if (form) {
            form.setFieldsValue({
                ...record,
                start_time: dayjs(record.start_time),
                end_time: dayjs(record.end_time),
                cover: imageUrl
            })
        }
    }

    //添加修改
    const addAndUpdateOk = async () => {
        if (newActivity) {
            try {
                const fd = {
                    ...form.getFieldValue(),
                    content1
                }
                await reqAddActivity({fd})
                message.success('添加活动成功!')
                setNewActivity(false)
                getActivityList()
            } catch (err) {
                message.error(err)
            }
        } else if (updateActivity) {
            try {
                const fd = {
                    ...form.getFieldValue(),
                    cover: imageUrl,
                    content1
                }
                console.log(fd)
                const result = await reqUpdateActivity({activity_id: activityId, fd})
                if (result.status === 0) {
                    message.success('修改活动成功!')
                    setUpdateActivity(false)
                    getActivityList()
                } else {
                    message.error('修改失败')
                }
            } catch (err) {
                message.error(err)
            }
        }
    }

    const deleteActivity = (id) => {
        setOpen(true);
        setActivityId(id)
    };

    //删除操作成功
    const deleteActivityOk = async () => {
        try {
            setModalText('即将删除成功!')
            setConfirmLoading(true);
            const result = await reqDeleteActivity({activity_id: activityId})
            if (result.status === 0) {
                setTimeout(async () => {
                    await getActivityList()
                    message.success('删除成功！')
                    setOpen(false);
                    setConfirmLoading(false);
                }, 1000);
            } else {
                message.error('删除失败！')
            }
        } catch (err) {
            message.error(err)
        }
    };
    const deleteCancel = () => {
        setOpen(false);
    };

    const searchActivity = debounce(async (e) => {
        const result = await reqGetActivityList()
        setActivityListData(result.data.filter((item) => item.activity_name.indexOf(e.target.value) !== -1))
    }, 500)


    const handleChangeValue = (e) => {
        // console.log(e)
        setContent(e)
    }

    const timeSortChange = async (value) => {
        const result = await reqGetActivityList()
        result.data.forEach((item) => {
            item.start_time = new Date(item.start_time);
        })
        if (value === '时间升序') {
            const newList = result.data.sort((a, b) => {
                return a.start_time.getTime() - b.start_time.getTime()
            });
            setActivityListData(newList)
        } else {
            const newList = result.data.sort((a, b) => {
                return b.start_time.getTime() - a.start_time.getTime()
            });
            setActivityListData(newList)
        }
    };

    //上传图片
    const uploadHandleChange = (info) => {
        if (info.file.status === 'uploading') {
            setEditCoverLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, (url) => {
                setEditCoverLoading(false);
                setImageUrl([url]);
            });
        }
    };
    const customRequest = async (options) => {
        // console.log(options)
        const {onSuccess, onError, file} = options;
        const fmData = new FormData()
        const config = {
            headers: {"content-type": "multipart/form-data"},
        };
        fmData.append("file", file);
        try {
            const res = await axios.post(
                `${process.env.REACT_APP_API_URL}/admin/activity-page/uploads`,
                fmData,
                config
            );
            const {url} = res.data;
            const fileObj = {
                uid: res.data.id,
                name: file.name,
                status: "done",
                url,
            };
            onSuccess(fileObj);
            console.log("server res: ", res);
        } catch (err) {
            console.log("Error: ", err);
            const error = new Error("Some error");
            onError(err);
        }
    }
    const normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList
    }
    const uploadButton = (
        <div>
            {editCoverLoading ? <LoadingOutlined/> : <PlusOutlined/>}
            <div style={{marginTop: 8}}>
                Upload
            </div>
        </div>
    );

    const chooseFormRef = useRef()

    return (
        <div>
            <Card>

                <div style={{display: 'flex', justifyContent: 'space-between',alignItems:'start'}}>
                    <Space>
                        <Button disabled={newActivity || updateActivity} type="primary"
                                onClick={addNewActivity}>
                            {
                                updateActivity ? '修改' : '新增+'
                            }
                        </Button>

                        {
                            (newActivity || updateActivity) &&
                            <Button onClick={() => {
                                cancel()
                            }}>取消</Button>
                        }
                    </Space>
                    {
                        newActivity || updateActivity ?
                            null :
                            <Form ref={chooseFormRef} style={{display: 'flex'}} name="chooseForm">
                                <Space>
                                    <Form.Item  name="select">
                                        <Select
                                            style={{width: 120}}
                                            onChange={timeSortChange}
                                            placeholder="按时间筛选"
                                            options={[
                                                {
                                                    value: '时间升序',
                                                    label: '时间升序',
                                                },
                                                {
                                                    value: '时间降序',
                                                    label: '时间降序',
                                                },
                                            ]}
                                        />
                                    </Form.Item>
                                    <Form.Item name="search">

                                        <Input.Search  onChange={searchActivity}
                                                      placeholder="根据活动名称搜索"></Input.Search>
                                    </Form.Item>
                                    <Form.Item>
                                        <Button onClick={() => {
                                            getActivityList()
                                            chooseFormRef.current.resetFields()
                                        }}>重置</Button>
                                    </Form.Item>
                                </Space>
                            </Form>
                    }
                </div>
                {
                    newActivity || updateActivity ?
                        <>
                            <Form
                                form={form}
                                labelCol={{span: 8}}
                                wrapperCol={{span: 18}}
                                layout="horizontal"
                                style={{display: 'flex', width: "100%", paddingBottom: 50}}
                                onFinish={() => addAndUpdateOk()}
                            >
                                <div style={{width: 600, marginRight: 80}}>
                                    <Form.Item label="活动名称" name="activity_name"
                                               rules={[{required: true, message: "请输入活动名称!"}]}
                                    >
                                        <Input/>
                                    </Form.Item>
                                    <Form.Item label="地点选择" name="place"
                                               rules={[{required: true, message: "请选择地点!"}]}
                                    >
                                        <Cascader
                                            options={options}
                                        />
                                    </Form.Item>
                                    <Form.Item label="开始报名时间" name="start_time"
                                               rules={[{required: true, message: "请选择报名时间!"}]}
                                    >
                                        <DatePicker placeholder="选择时间"/>
                                    </Form.Item>
                                    <Form.Item label="截止时间" name="end_time"
                                               rules={[{required: true, message: "请选择截止时间!"}]}
                                    >
                                        <DatePicker placeholder="选择时间"/>
                                    </Form.Item>
                                    <Form.Item label="人数上限" name="p_num"
                                               rules={[{required: true, message: "请输入活动人数!"}]}
                                    >
                                        <InputNumber min={1}/>
                                    </Form.Item>
                                    <Form.Item
                                        label="活动封面"
                                        name="cover"
                                        valuePropName="fileList"
                                        getValueFromEvent={normFile}
                                    >
                                        <Upload
                                            listType="picture-card"
                                            showUploadList={false}
                                            beforeUpload={beforeUpload}
                                            onChange={uploadHandleChange}
                                            customRequest={customRequest}
                                            maxCount={1}
                                        >
                                            {imageUrl ? (
                                                <img
                                                    alt="文章封面"
                                                    src={imageUrl}
                                                    style={{width: 100}}/>
                                            ) : (
                                                uploadButton
                                            )}
                                        </Upload>
                                    </Form.Item>
                                </div>
                                <div>
                                    <Form.Item>
                                        <ReactQuill
                                            theme="snow"
                                            style={{width: 600, height: 400}}
                                            placeholder="请输入活动详情"
                                            preserveWhitespace
                                            modules={modules}
                                            value={content1}
                                            onChange={handleChangeValue}
                                        />
                                    </Form.Item>
                                </div>
                                <Form.Item style={{position: 'absolute', bottom: 0, right: 250}}>
                                    <Button type="primary" htmlType="submit">保存</Button>
                                </Form.Item>
                            </Form>
                        </>
                        :
                        <Table
                            scroll={{y: 555}}
                            rowKey={record => record.id}
                            columns={columns}
                            dataSource={activityListData}
                        />
                }

            </Card>

            <Modal
                title="删除活动"
                centered
                open={open}
                onOk={deleteActivityOk}
                confirmLoading={confirmLoading}
                onCancel={deleteCancel}
                okText="确认"
                cancelText="取消"
            >
                <p>{modalText}</p>
            </Modal>
        </div>
    );
};

export default AdminActivity;